using System.Diagnostics;
using System.Linq;
using LuceneSearch.ContactApp.Repositories;
using NHibernate;

namespace LuceneSearch.ContactApp.Searching
{
    public class IndexedEntitySearcher<T> where T : class
    {
        private readonly EntityQueryBuilder<T> entityQueryBuilder;
        private readonly EntityQueryExecutor<T> entityQueryExecutor;
        private readonly Repository<T> repository;

        public IndexedEntitySearcher(EntityQueryBuilder<T> entityQueryBuilder, EntityQueryExecutor<T> entityQueryExecutor, Repository<T> repository)
        {
            this.entityQueryBuilder = entityQueryBuilder;
            this.entityQueryExecutor = entityQueryExecutor;
            this.repository = repository;
        }

        public SearchResult<T> Search(ISession session, T entityCriteria)
        {
            var query = entityQueryBuilder.BuildQuery(entityCriteria);

            var stopwatch = new Stopwatch();

            stopwatch.Start();
            var resultIds = entityQueryExecutor.QueryAndReturnIds(query);
            stopwatch.Stop();

            var elapsed = stopwatch.Elapsed;

            var totalFound = resultIds.Count();
            var idsToReturn = resultIds.Where(IsTop100).ToArray();
            var contacts = repository.FindByIds(session, idsToReturn);

            return new SearchResult<T>
                       {
                           NumberOfResultsFound = totalFound, 
                           Results = contacts,
                           SearchTime = elapsed
                       };
        }

        private static bool IsTop100(int id, int index)
        {
            return index < 100;
        }
    }
}